package cn.mldn.experiment.BIOwithMultiThread;

import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class BIOMultiThreadServer
{
	public static void main(String[] args) throws IOException, InterruptedIOException
	{
		ServerSocket serverSocket = new ServerSocket(8888);
		System.out.println("服务器已开启，等待客户端连接---");

		while (true)
		{
			final Socket socket = serverSocket.accept();
			System.out.println("客户端连接服务器了---");

			new Thread(new Runnable()
			{
				@Override
				public void run()
				{
					try
					{
						OutputStream outputStream = socket.getOutputStream();
						InputStream inputStream = socket.getInputStream();
						String msg = "";

						while (true)
						{
							byte[] b = new byte[1024];
							int len = inputStream.read();
							if (len == -1)
							{
								continue;
							}

							msg = new String(b, 0, len);

							System.out.println("收到客户端发送的数据：" + msg);
							outputStream.write(("服务器已收到数据：" + msg).getBytes());
						}
					} catch (IOException e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

			}).start();

			socket.close(); // 关闭客户端
		}
	}
}